<?php

// Get the Global Vars
require_once(dirname(__FILE__) . "/GlobalsClass.php"); // Needed for UTK server (works w/Win too)
// Get the XML-making strategy obj
require_once(dirname(__FILE__) . "/Lib/XmlJobMaker.php"); 
require_once(dirname(__FILE__) . "/Lib/Params_Task.php"); 
require_once(dirname(__FILE__) . "/Lib/Params_Image.php"); 

///////////////////////////////////////
///// Fake values used for testing ////

// Job Metadata
$status  = "done";
$jobName = "BigPart123";
$jobAltname = "The moneymaker";

    //$authorLastname = "webuser";
    //$authorFirstname = null;
    //$authorMiddlename = null;
$author = "webuser";
// The file & path of the XML file to be created
$outFileFullPath =    GlobalsClass::getXmlJobSavePath() . "job_test_fdk.xml";  
$configFileFullPath = GlobalsClass::getXmlJobSavePath() . "config.txt";  
$tagsArray = array("Big", "Metal", "Experimental", "Part 152", "_Special", "Priority:High");
$descrip  = "These images are from the government contract secured by Stevenson last month.  We had to run the tests 3 times using the new XYZ technique.  We should consider trying technique YYZ next time.";
$debug = false;


///////////////////////////////////////////
//////// Image processing parameters //////
// ------------------
// ---- <task> ------
$user_task_type = TaskType::PSIRT;  // TODO: Put TaskType in Globals?  So input form can use those enums too?

switch($user_task_type) {

  case TaskType::FDK:
    $paramsTask = new Params_Task($user_task_type);
        // Testing setting vals:
        $paramsTask->FDK->filter = 2;  
        //$paramsTask->FDK->alpha  = 1.34;  // intentionally invalid value for testing
    break;
  
  case TaskType::PSIRT:
    $paramsTask = new Params_Task($user_task_type);
        // Testing setting vals:
        $paramsTask->PSIRT->alpha = 1.6;
        $paramsTask->PSIRT->Niter = 2;
        $paramsTask->PSIRT->Nsubs = 3;
        $paramsTask->PSIRT->subset_modeX = 21;
        //$paramsTask->PSIRT->subset_modeX = 17;  // intentionally invalid value for testing
        $paramsTask->PSIRT->subset_modeY = 'B';
        $paramsTask->PSIRT->outputmodulo = 2;
    break;
  
  case TaskType::SIRT:
    $paramsTask = new Params_Task($user_task_type);
        // Testing setting vals:
        $paramsTask->SIRT->alpha = 1.6;
        $paramsTask->SIRT->Niter = 2;
        $paramsTask->SIRT->Nsubs = 3;
        $paramsTask->SIRT->subset_modeX = 21;
        $paramsTask->SIRT->subset_modeY = 'B';
        $paramsTask->SIRT->outputmodulo = 2;
    break;
  
  case TaskType::FULLDATA:    // empty element - no properties to set
    $paramsTask = new Params_Task($user_task_type);
    break;
  case TaskType::ROIDATA:     // empty element - no properties to set
    $paramsTask = new Params_Task($user_task_type);
    break;
  case TaskType::ROIXYZ:      
    $paramsTask = new Params_Task($user_task_type);
        // Testing setting vals:
        $paramsTask->ROIXYZ = 1;
    break;
  case TaskType::RECON_NONE:  // empty element - no properties to set
    $paramsTask = new Params_Task($user_task_type);
    break;
  default:
} ////// end swith(user_task_type) ///////

// -------------------
// ---- <image> ------
//
// REQUIRED children of <image> (need to prepare these to instantiate a Params_Image)
$imageType = ImageType::F32;
$IMAGE = new IMAGE();
    // Testing setting vals:
    $IMAGE->Nx = 0;
    $IMAGE->Ny = 0;
    $IMAGE->Nz = 0;
$COMPROI = new COMPROI();
    $COMPROI->comproi = 3;
    $COMPROI->foa_threshold = 1.2;
    $COMPROI->foa_outsidemax = 3.2;
$VOXEL = new VOXEL();
    $VOXEL->dxy =  .7;
    $VOXEL->dz  = 2.4;

$paramsImage = new Params_Image($imageType, $IMAGE, $COMPROI, $VOXEL);

// OPTIONAL children of <image>
if(true) {
  $paramsImage->ROI_X = new ROI_type();
    $paramsImage->ROI_X->roi_0 =  1;
    $paramsImage->ROI_X->roi_1 = -1;
}
if(true) {
  $paramsImage->ROI_Y = new ROI_type();
    $paramsImage->ROI_Y->roi_0 =  1;
    $paramsImage->ROI_Y->roi_1 = -1;
}
if(true) {
  $paramsImage->ROI_Z = new ROI_type();
    $paramsImage->ROI_Z->roi_0 =  1;
    $paramsImage->ROI_Z->roi_1 = -1;
}

if(true) {
  $paramsImage->IMG_INDIR = new IMG_INDIR();
    $paramsImage->IMG_INDIR->indir = "_some_directory_";
}
if(true) {
  $paramsImage->IMG_OUTDIR = new IMG_OUTDIR();
    $paramsImage->IMG_OUTDIR->outdir = "_some_directory_";
}

if(true) {
  $paramsImage->CLIP = new CLIP();
    $paramsImage->CLIP->clipmin = 1.54;
    $paramsImage->CLIP->clipmax = 4.12;
}
//// end fake values ////////////
/////////////////////////////////


$xmlJobMaker = new XmlJobMaker($status, $jobName, $jobAltname, 
                       /*$authorFirstname, $authorMiddlename, $authorLastname,*/
                       $author,
                       $paramsTask, $paramsImage, $paramsProj, $paramsMiscl, 
                       $outFileFullPath, 
                       $configFileFullPath,
                       $tagsArray, 
                       $descrip, 
                       /* debug: */ false);

$result = $xmlJobMaker->makeAndValidateXmlJob(); // Creates and validates xml doc, then writes it to disk



if($result !== true) {  // Note: must test it like this since an error string can be interpreted 'true'
  printD("\n<p>xmlJobMaker->makeAndValidateXmlJob() returned: \"$result\"</p>");
  printD("\n<p>Error creating, validating or saving xml document.  Exiting now.</p>");
  exit();
}


print("\n<p>Supposedly the XML was written to file: $outFileFullPath</p>\n");
  // print("\n<p>Here is where makeXmlCallC.php would call the C program to parse the XML document</p>\n");





/////////////////////////////////////////////////
///// PREPARE TO SUBMIT JOB TO CUDA CLUSTER /////

// TODO: Prepare/create the job directory... copy header.txt, etc.

$reconCodeFullPath = "/home/jfrank3/webhome/imagerecon/Tests/helloWorld";


generateCudaScript($jobName, $jobDir, $dataDir, $reconCodeFullPath);
//submitJobToCuda();


function generateCudaScript($jobName, $jobDir, $dataDir, $reconCodeName) {
  
$shScriptStr = <<<HEREDOC
#!/bin/sh 
#PBS -l nodes=4:ppn=8
#PBS -l walltime=10:00:00

source /usr/local/modules/init/sh > /dev/null
module load openmpi-eecs
 
HEREDOC;

//  $shScriptStr .= "BASE="
  
  //TODO: Finish this
  
} /////// end function generateCudaScript() ///////////


function submitJobToCuda() {
   
  $privateKeyFullPath = GlobalsClass::getPrivateKeyFullPath();

  $outputArray = array();        
  $submitScript = "/home/jfrank3/webhome/imagerecon/Tests/cudaSubmit_helloWorld";
  $initCuda = "source /usr/local/modules/init/zsh";
  $loadTorque = "module load torque";

  $cudaUser = 'jfrank3'; // user account on cuda
  // cd to this dir so cudahead's stdout/stderr files get placed there
  $outFileDir = "/home/jfrank3/webhome/imagerecon/Tests/"; 

  $cmdStr = "ssh -i $privateKeyFullPath $cudaUser@cudahead '$initCuda; $loadTorque; "
           ."showq; cd $outFileDir; qsub $submitScript'";
  
  printD("About to execute: $cmdStr");
  $lastLine = exec($cmdStr, $outputArray, $returnStatus);
  printD("\nReturn status of the exec() call was: $returnStatus");
  printD("\nOutput array was:");
  foreach($outputArray as $line) {
      printD("\n$line\"");
  }
} //////// end function submitJobToCuda() /////////////




function printD($str) {
  global $debug;
  if($debug) print($str);
} /////// end function printD() /////

?>
